import { NextRequest, NextResponse } from 'next/server';

// Chromium
import chromium from '@sparticuz/chromium';

// Helpers
import { getInvoiceTemplate } from '@/lib/helpers';

// Variables
import { CHROMIUM_EXECUTABLE_PATH, ENV, TAILWIND_CDN } from '@/lib/variables';

// Types
import { InvoiceType } from '@/types';

export const generatePdfService = async (req: NextRequest) => {
    const body: InvoiceType = await req.json();

    let browser;
    try {
        const ReactDomServer = (await import('react-dom/server')).default;

        const templateId = body.details.pdfTemplate;

        const InvoiceTemplate = await getInvoiceTemplate(templateId);

        const htmlTemplate = ReactDomServer.renderToStaticMarkup(InvoiceTemplate(body));

        const puppeteer = (await import('puppeteer')).default;

        if (ENV === 'production') {
            browser = await puppeteer.launch({
                args: chromium.args,
                defaultViewport: chromium.defaultViewport,
                executablePath: await chromium.executablePath(CHROMIUM_EXECUTABLE_PATH),
                headless: true,
                // ignoreHTTPSErrors: true,
            });
        } else if (ENV === 'development') {
            browser = await puppeteer.launch({
                args: ['--no-sandbox', '--disable-setuid-sandbox'],
                headless: true,
            });
        }

        if (!browser) {
            throw new Error('Failed to launch browser');
        }

        const page = await browser.newPage();
        console.log('Page opened');

        await page.setContent(htmlTemplate, {
            waitUntil: 'networkidle0',
        });

        console.log('Content set');

        await page.addStyleTag({ url: TAILWIND_CDN });

        const pdf = await page.pdf({
            format: 'A4',
            printBackground: true,
        });
        console.log('PDF generated');

        for (const openedPage of await browser.pages()) {
            await openedPage.close();
        }

        await browser.close();
        console.log('Browser closed');

        const pdfBlob = new Blob([pdf], { type: 'application/pdf' });

        const response = new NextResponse(pdfBlob, {
            headers: {
                'Content-Type': 'application/pdf',
                'Content-Disposition': 'inline; filename=invoice.pdf',
            },
            status: 200,
        });

        return response;
    } catch (error) {
        console.error('执行异常', error);

        // Return an error response
        return new NextResponse(`Error generating PDF: \n${error}`, {
            status: 500,
        });
    } finally {
        if (browser) {
            await Promise.race([browser.close(), browser.close(), browser.close()]);
        }
    }
};
